import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, Link } from 'react-router-dom';
import { Input, Select, Button, InputNumber, Pagination } from 'antd';
import MarketplaceABI from '../contract/ABIs/Marketplace.json'; // 用户列表合约 ABI
import MaterialListAddr from '../contract/ADDRESSes/MaterialListAddr';
import './ProductList.css'; // 引入CSS文件

const { Option } = Select;

const ProductList = () => {
    const { userAddr } = useParams();
    const [products, setProducts] = useState([]);
    const [filteredProducts, setFilteredProducts] = useState([]);
    const [category, setCategory] = useState('');
    const [minPrice, setMinPrice] = useState(0);
    const [maxPrice, setMaxPrice] = useState(0);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(5);
    const web3 = new Web3(window.ethereum);
    const marketplaceContract = new web3.eth.Contract(MarketplaceABI, MaterialListAddr);

    useEffect(() => {
        const fetchProducts = async () => {
            const productCount = await marketplaceContract.methods.productCount().call();
            const products = [];
            for (let i = 1; i <= productCount; i++) {
                const product = await marketplaceContract.methods.products(i).call();
                if (product.isAvailable) {
                    products.push(product);
                }
            }
            setProducts(products);
            setFilteredProducts(products);
        };
        fetchProducts();
    }, []);

    const handleFilter = () => {
        let filtered = products;
        if (category) {
            filtered = filtered.filter(product => product.category === category);
        }
        if (minPrice > 0) {
            filtered = filtered.filter(product => Number(product.price) >= minPrice);
        }
        if (maxPrice > 0) {
            filtered = filtered.filter(product => Number(product.price) <= maxPrice);
        }
        setFilteredProducts(filtered);
        setCurrentPage(1);
    };

    const handlePageChange = (page, pageSize) => {
        setCurrentPage(page);
        setPageSize(pageSize);
    };

    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedProducts = filteredProducts.slice(startIndex, endIndex);

    return (
        <div className="product-list-container">
            <h2 className="product-list-title">校园好物</h2>
            <div className="filter-container">
                <Select
                    placeholder="选择类别"
                    className="filter-select"
                    onChange={value => setCategory(value)}
                >
                    <Option value="">所有类别</Option>
                    <Option value="宠物">宠物</Option>
                    <Option value="电子产品">电子产品</Option>
                    <Option value="技术服务">技术服务</Option>
                    <Option value="服饰">服饰</Option>
                    <Option value="鞋包">鞋包</Option>
                    <Option value="宠生鲜类">生鲜</Option>
                    <Option value="其他">其他</Option>
                    {/* 根据实际类别添加更多选项 */}
                </Select>
                <InputNumber
                    placeholder="最低价格"
                    className="filter-input"
                    onChange={value => setMinPrice(value)}
                />
                <InputNumber
                    placeholder="最高价格"
                    className="filter-input"
                    onChange={value => setMaxPrice(value)}
                />
                <Button type="primary" onClick={handleFilter}>筛选</Button>
            </div>
            <div className="product-list">
                {paginatedProducts.map((product, index) => (
                    <div key={index} className="product-card">
                        <img src={`https://ipfs.infura.io/ipfs/${product.ipfsHash}`} alt={product.name} className="product-image" />
                        <div className="product-details">
                            <h3>{product.name}</h3>
                            <p>{product.description}</p>
                            <p>价格: {Number(product.price)} RMB</p>
                            <p>数量: {Number(product.quantity)}</p>
                            <Link to={`/index1/${userAddr}/ProductDetail/${product.id}`} className="product-link">查看详情</Link>
                        </div>
                    </div>
                ))}
            </div>
            <Pagination
                current={currentPage}
                pageSize={pageSize}
                total={filteredProducts.length}
                onChange={handlePageChange}
                showSizeChanger
                pageSizeOptions={['5', '10', '20']}
            />
        </div>
    );
};

export default ProductList;